/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.datatheorem.ohos.trustkit.pinning;

import com.datatheorem.ohos.trustkit.TrustKit;
import com.datatheorem.ohos.trustkit.config.DomainPinningPolicy;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

/**
 * {@link X509TrustManager} used for Certificate Pinning.
 *
 * <p>This trust manager delegates to the appropriate {@link PinningTrustManager} decided by the
 * hostname set by the {@link OkHttp3PinningInterceptor}.</p>
 */
class OkHttpRootTrustManager implements X509TrustManager {
    private final ThreadLocal<String> mServerHostname = new ThreadLocal<>();

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        TrustKit.getInstance().getTrustManager(mServerHostname.get()).checkClientTrusted(chain, authType);
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        String host = mServerHostname.get();
        DomainPinningPolicy serverConfig =
                TrustKit.getInstance().getConfiguration().getPolicyForHostname(host);
        X509TrustManager trustManager = TrustKit.getInstance().getTrustManager(host);

        //The first check is needed for compatibility with the Platform default's implementation of
        //the Trust Manager. For APIs 24 and greater, the Platform's default TrustManager states
        //that it requires usage of the hostname-aware version of checkServerTrusted for app's that
        if (serverConfig == null) {
            //TODO 暂无该方法
//            new X509TrustManagerExtensions(trustManager).checkServerTrusted(chain, authType, host);
        } else {
            trustManager.checkServerTrusted(chain, authType);
        }
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }

    void setServerHostname( String serverHostname) {
        mServerHostname.set(serverHostname);
    }
}

